﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Calculates the mean of an image.
    /// </summary>
    public class Mean : BaseImageFilter
    {
        /// <summary>
        /// 
        /// </summary>
        public Mean()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Mean"/> class.
        /// </summary>
        /// <param name="_mean">The _mean.</param>
        internal Mean(Mean _mean)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;
            BitmapData data = bitmap.BitmapData; //bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            int[] pixelValues = new int[100];

            int y = 0;
            int x = 0;
            int a = 0;
            int h = bitmap.Height;
            int w = bitmap.Width;
            int b = 0;
            int[] pixel = new int[h * w];
            int[] pixeln = new int[w + 2];
            int count = 0;
            for (y = 0; y < h - 5; y++)
            {
                for (x = 0; x < w - 5; x++)
                {
                    count = 0;
                    for (a = 0; a < 5; a++)
                    {
                        for (b = 0; b < 5; b++)
                        {
                            pixelValues[count] = pixel[b + w * a];
                            count++;
                        }
                    }
                    Array.Sort(pixelValues);
                    pixeln[1 + w * 1] = pixelValues[count / 2];
                    //pixel++; pixeln++;
                }
            }

            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new Mean(this);
        }
    }
}
